package com.xujie.sportsmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.sportsmeeting.entity.CompetitionEvent;
import com.xujie.sportsmeeting.entity.EventRegistration;
import com.xujie.sportsmeeting.mapper.CompetitionEventMapper;
import com.xujie.sportsmeeting.mapper.EventRegistrationMapper;
import com.xujie.sportsmeeting.service.CompetitionEventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 比赛项目服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CompetitionEventServiceImpl extends ServiceImpl<CompetitionEventMapper, CompetitionEvent> implements CompetitionEventService {

    private final EventRegistrationMapper eventRegistrationMapper;

    @Override
    public CompetitionEvent findByEventCode(String eventCode) {
        LambdaQueryWrapper<CompetitionEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompetitionEvent::getEventCode, eventCode);
        return getOne(wrapper);
    }

    @Override
    public boolean existsByEventCode(String eventCode) {
        LambdaQueryWrapper<CompetitionEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompetitionEvent::getEventCode, eventCode);
        return count(wrapper) > 0;
    }

    @Override
    public boolean canRegister(Long eventId) {
        CompetitionEvent event = getById(eventId);
        if (event == null) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        
        // 检查项目状态
        if (event.getStatus() != 2) { // 2-报名中
            return false;
        }

        // 检查报名时间
        if (event.getRegistrationStartTime() != null && now.isBefore(event.getRegistrationStartTime())) {
            return false;
        }

        if (event.getRegistrationEndTime() != null && now.isAfter(event.getRegistrationEndTime())) {
            return false;
        }

        // 检查报名人数是否已满
        long registrationCount = getRegistrationCount(eventId);
        return registrationCount < event.getMaxParticipants();
    }

    @Override
    public long getRegistrationCount(Long eventId) {
        LambdaQueryWrapper<EventRegistration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventRegistration::getEventId, eventId)
               .eq(EventRegistration::getStatus, 1)
               .in(EventRegistration::getAuditStatus, 0, 1); // 待审核和已通过
        return eventRegistrationMapper.selectCount(wrapper);
    }

    @Override
    public boolean updateEventStatus(Long eventId, Integer status) {
        CompetitionEvent event = new CompetitionEvent();
        event.setId(eventId);
        event.setStatus(status);
        return updateById(event);
    }
}
